using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace TestProject
{
	public class BookController : Controller
	{
		public static List<Book> searchedBooks = new List<Book>(0);
		public static List<Book> filteredBookList = new List<Book>(0);
		
		public object filtersearchedBooks(int index)
		{
			List<Book> filteredBook =  Book.filtersearchedBooks(index, filteredBookList);
			
			System.Web.Script.Serialization.JavaScriptSerializer serializeThis = new System.Web.Script.Serialization.JavaScriptSerializer();
			return  serializeThis.Serialize(filteredBook);
		}
		
		public List<Book> getBooks()
		{
			filteredBookList = searchedBooks = TestProject.Book.getBooks();			
			return searchedBooks;
		}
		
		
		public object SearchBook(string search)
		{
			List<Book> searchedBook = TestProject.Book.searchBooks(search,searchedBooks);
			filteredBookList = searchedBook;
			System.Web.Script.Serialization.JavaScriptSerializer serializeThis = new System.Web.Script.Serialization.JavaScriptSerializer();
			return  serializeThis.Serialize(searchedBook);
		}
		
		[HttpPost]
		public string LookupAWSByISBN(string isbn)
		{
			AmazonWebService.AmazonWSBook awsBook = null;
			
			try {
				awsBook = AmazonWebService.AmazonWSBook.GetBookByISBN(isbn);
			}
			catch (Exception ex) {
				if (ex.GetType().Equals(typeof(System.ServiceModel.EndpointNotFoundException))) {
					Console.WriteLine("Encountered System.ServiceModel.EndpointNotFoundException!");
					Console.WriteLine("Couldn't connect to Amazon, please check your internet connection.");
					return "1";
				}else if (ex.GetType().Equals(typeof(System.ServiceModel.CommunicationException))) {
					Console.WriteLine("Encountered System.ServiceModel.CommunicationException!");
					Console.WriteLine("Search Result Page too long, please try a different search string(s).");
					return "2";
				}else if (ex.GetType().Equals(typeof(System.NullReferenceException))) {
					Console.WriteLine("Encountered System.NullReferenceException!");
					Console.WriteLine("Search Result Page returned empty, maximum Search Result Page No. exceeded.");
					return "3";
				}
			}
						
			System.Web.Script.Serialization.JavaScriptSerializer serializeThis = new System.Web.Script.Serialization.JavaScriptSerializer();
			return  serializeThis.Serialize(awsBook);
		}
		
		[HttpPost]
		public string AddBook(string isbn, string title, string author, string image, string synopsis, string publisher, string genre, string callNo)
		{
			
			//Search for existing ISBN Number
			title = title.Replace("'","\\'");
			publisher = publisher.Replace("'","\\'");
			synopsis =  synopsis.Replace("'","\\'");
			bool existingISBN = false;
			int i;
			for(i= 0; i< searchedBooks.Count; i++)
			{
				if(searchedBooks[i].isbn.ToLower().Contains(isbn.ToLower()))
				{
					existingISBN = true;
					break;
				}
			}
			
			if(existingISBN == true)
			{
				return searchedBooks[i].book_ID.ToString();
			}
			else
			{
				HttpPostedFileBase file =  Request.Files[image];
				string fileName;
				if(file != null) // File upload is not yet working. file is always null - will check ASAP.
				{
					fileName = isbn+".jpg";
					string path =  Server.MapPath("~/Images/BookPictures/"+fileName);
					file.SaveAs(path);
				}
				else
				{
					fileName = "/Images/BookPictures/default.jpg";
				}
				
				Book book = TestProject.Book.addBook(isbn, title, author, fileName, synopsis, publisher);	
				searchedBooks.Add(book);
				
				//Adding Genres
				if(genre != "")
				{
					var arr = genre.Split(',');
					List<Genre> genreList = new List<Genre>(0);
					for(i = 0; i < arr.Length; i++)
					{
						Genre l_genre = new Genre( Int32.Parse(arr[i]));
						genreList.Add(l_genre);
					}
					book.addGenre(genreList);
				}
				
				//Adding a copy
				TestProject.Copy.addCopy(book.book_ID, callNo);
				
				
				System.Web.Script.Serialization.JavaScriptSerializer serializeThis = new System.Web.Script.Serialization.JavaScriptSerializer();
				return  serializeThis.Serialize(book);
			}
			
			
		}
		
		[HttpPost]
		public void deleteBook(int book_id)
		{
			TestProject.Book.deleteBook(book_id);
		}
		
		[HttpPost]
		public void editBook(int book_id, string isbn, string title, string author, string synopsis, string publisher, string genre)
		{
			Book searched = searchedBooks.Find(delegate(Book b){ return b.book_ID == book_id;});
		
			int index = searchedBooks.FindIndex(delegate(Book b){ return b.book_ID == book_id;});
			
			searchedBooks[index].isbn = isbn;
			searchedBooks[index].author = author;
			searchedBooks[index].publisher = publisher;
			searchedBooks[index].synopsis = synopsis;
			searchedBooks[index].title = title;
			
			title = title.Replace("'","\\'");
			author = author.Replace("'","\\'");
			publisher = publisher.Replace("'","\\'");
			synopsis =  synopsis.Replace("'","\\'");
			
			TestProject.Book.editBook(book_id, isbn, title, author, synopsis, publisher);
			List<Genre> genreList = new List<Genre>(0);
			if(genre != "")
			{
				string[] arr = genre.Split(',');
				for(int i = 0; i < arr.Length; i++)
				{
					Genre l_genre = new Genre( int.Parse(arr[i]));
					genreList.Add(l_genre);
				}
				
			}
			searched.updateGenres(genreList);
		}
		
		public void reserveBook(int user_ID, int book_ID)
		{
			Reservation.addReservation(book_ID,user_ID);
		}
		
		public ActionResult Manage()
		{
			ViewData["Books"] = BookController.filteredBookList = BookController.searchedBooks;
			ViewData["Genre"] = TestProject.Genre.getAllGenres();
			return View();
		}
		
		public ActionResult Profile(string id)
		{
			Book bookProfile = TestProject.Book.searchBookByISBN(id, searchedBooks);
			List<Reservation> reservations = Book.getReservations(bookProfile.book_ID);
			if (Session["level"]!=null)			
				ViewData["isReserved"] = Book.isReserved(bookProfile.book_ID, (int)Session["user_id"]);
			ViewData["reservations"] = reservations;
			ViewData["available"] = Book.getAvailableCopies(bookProfile.book_ID).Count;
			Console.WriteLine(Book.getAvailableCopies(bookProfile.book_ID).Count);
			ViewData["Genres"] = bookProfile.getGenres();
			ViewData["AllGenres"] = TestProject.Genre.getAllGenres();
			ViewData["Book"] = bookProfile;
			List<Copy> copies = bookProfile.getCopies();
			for (int i=0; i<copies.Count; i++)
				copies[i].getCurrentLoan();
			ViewData["Copies"] = copies;
			return View();
		}
		
		public ActionResult Reserve(int id)
		{
			Copy copy = new Copy(id);
			Reservation latest = new Reservation();
			Book book = new Book(copy.book_ID);
			ViewData["Reservations"] = copy.getReservations();
			ViewData["callNo"] = copy.callNo;
			ViewData["LoanRange"] = Loan.loan_range;
			ViewData["Book"] = book;
			ViewData["copy_id"] = id;
			return View();
		}
		
		public object getReservationDates(int copy_id)		{
			List<Reservation> reservations = Copy.getReservations(copy_id);
			
			System.Web.Script.Serialization.JavaScriptSerializer serializeThis = new System.Web.Script.Serialization.JavaScriptSerializer();
			
			return  serializeThis.Serialize(reservations);
		}
		
		public void AddCopy(string isbn, string callNo)
		{
			Book book = Book.searchBookByISBN(isbn,searchedBooks);
			Copy.addCopy(book.book_ID, callNo);
		}
		
		public void editCopy(int copy_id, string callNo)
		{
			Copy.editCopy(copy_id,callNo);
		}
		
		public ActionResult Reservations()
		{
			ViewData["Queue"] = Reservation.getReservations();
			return View();
		}
		
		public ActionResult Loans()
		{
			return View();
		}
		
		public ActionResult Lend(int id)
		{
			Reservation reservation= new Reservation(id);
			ViewData["reservation"] = id;
			ViewData["user"] = new User(reservation.user_ID);
			ViewData["book"] = new Book(reservation.book_ID);
			ViewData["currentDate"] = DateTime.Now.ToString("MMM d, yyyy");
			ViewData["endDate"] = DateTime.Now.AddDays(4).ToString("MMM d, yyyy");
			return View();
		}
		
		public bool lendBook(int user_ID, int book_ID, DateTime startdate, DateTime enddate, int reservation_ID)
		{
			List<Copy> copies = Book.getAvailableCopies(book_ID);
			if (copies.Count<= 0)
				return false;
			else{
				Loan.adminAddLoan(copies[0].copy_ID, user_ID, startdate, enddate);
				Reservation.deleteReservation(reservation_ID);
				return true;
			}
		}
		
		
	}
}

